package com.jdbc1234.shiro;

import com.jdbc1234.common.ShiroUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

/**
 * 基于角色的访问控制
 * @author : 章仕烜
 * @create : 2019/12/19
 **/
public class RoleTest {

//    @Test
    public void testHasRole(){
        Subject currentUser = ShiroUtils
                .login("classpath:shiro_role.ini",
                        "java1234",
                        "123456");
        System.err.println(currentUser.hasRole("role1")?"有role1":"无role1");
        currentUser.logout();
    }

    public void testHasRoles(){
        Subject currentUser = ShiroUtils
                .login("classpath:shiro_role.ini",
                "java1234",
                "123456");
        boolean[] results = currentUser.hasRoles(Arrays.asList(
                "role1","role2","role3","role4"
        ));
        System.err.println(Arrays.toString(results));
        System.err.println(currentUser.hasAllRoles(Arrays.asList("role1","role2"))
                ?"role1,role2全有":"role1,role2不全有");
    }

    public void testCheckRole(){
        Subject currentUser = ShiroUtils
                .login("classpath:shiro_role.ini",
                        "java1234",
                        "123456");
        // checkRole、checkRoles走的是异常流，当没有这个角色时会抛出异常
        try {
            currentUser.checkRole("role1");
        } catch (AuthorizationException e) {
            e.printStackTrace();
        }
        // check系列没有返回值，一旦subject(user)没有其中一个角色就报错
        try {
            currentUser.checkRoles(Arrays.asList(
                    "role1","role2"
    //                ,"role3","role4"
            ));
        } catch (AuthorizationException e) {
            e.printStackTrace();
        }
        currentUser.logout();
    }


    public static void main(String[] args) {
        RoleTest roleTest= new RoleTest();
        roleTest.testCheckRole();
    }
}
